package com.knowledge.knowledge_notes.controller;

import com.knowledge.knowledge_notes.annotation.ApiRestController;
import com.knowledge.knowledge_notes.common.ResultVo;
import com.knowledge.knowledge_notes.common.constant.CommonConstant;
import com.knowledge.knowledge_notes.pojo.LoginUser;
import com.knowledge.knowledge_notes.service.UserService;
import com.knowledge.knowledge_notes.util.JwtUtil;
import com.knowledge.knowledge_notes.util.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@ApiRestController
public class LoginController {

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginUser requestUser) {
        Map<String,Object> result = new HashMap<>();
        String username = requestUser.getUserName();
        String syspassword = requestUser.getPassword();
        try {
            LoginUser user = userService.findByUserName(username);
            if (!user.isEnabled()) {
                String message = "该用户已被禁用";
                return ResultVo.FAIL(message);
            }
            // 生成token
            String token = JwtUtil.sign(username, syspassword);
            // 设置token缓存有效时间
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);
            Map<String,Object> userInfo = new HashMap<>();
            userInfo.put("userName",user.getUserName());
            userInfo.put("name",user.getName());
            result.put("user",userInfo);
            result.put("token",token);
            return ResultVo.OK(result);
        } catch (AuthenticationException e) {
            String message = "账号密码错误";
            return ResultVo.FAIL(message);
        }
    }

    @GetMapping("/logout")
    public ResultVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        String message = "成功登出";
        return ResultVo.OK(message);

    }



    @PostMapping("/register")
    public ResultVo register(@RequestBody LoginUser user) {
        String username = user.getUserName();
        String password = user.getPassword();
        username = HtmlUtils.htmlEscape(username);
        user.setUserName(username);
        boolean exist = userService.isExist(username);
        if (exist) {
            return ResultVo.FAIL("用户名已被使用");
        }
        // 生成盐,默认长度 16 位
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        // 设置 hash 算法迭代次数
        int times = 2;
        // 得到 hash 后的密码
        String encodedPassword = new SimpleHash("md5", password, salt, times).toString();
        // 存储用户信息，包括 salt 与 hash 后的密码
        user.setSalt(salt);
        user.setPassword(encodedPassword);
        userService.add(user);
        return ResultVo.OK(user);

    }

//    @CrossOrigin
    @GetMapping(value = "/authentication")
    public String authentication(){
        return "身份认证成功";
    }

}
